package com.lun.swordtowardoffer2.c08;

import com.lun.util.BinaryTree.TreeNode;

public class SerializeAndDeserializeBinaryTree {

	public String serialize(TreeNode node){
		if(node == null)
			return "#";
		
		return String.format("%s,%s,%s", node.val, serialize(node.left), // 
				serialize(node.right));
	}
	
	public TreeNode deserialize(String data) {
		String[] nodeStrs = data.split(",");
		int[] index = {0};//传引用, 类似传指针
		return dfs(nodeStrs, index);
	}
	
	private TreeNode dfs(String[] nodeStrs, int[] index) {
		String str = nodeStrs[index[0]++];
		
		if(str.equals("#"))
			return null;
		
		TreeNode node = new TreeNode(Integer.parseInt(str));
		node.left = dfs(nodeStrs, index);
		node.right = dfs(nodeStrs, index);
		return node;
	}
	
}
